package com.example.seakdreamandroid.sleep;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.Result;
import com.example.seakdreamandroid.entity.User;

import com.example.seakdreamandroid.sleep.entity.History;
import com.example.seakdreamandroid.sleep.entity.SleepInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RecordPage extends AppCompatActivity {

    private TextView arpSleep,arpWeakUp,arpSleepDay,arpWeakUpDay;
    private SleepInfo sleepInfo;
    private TextView cur,length;
    private SeekBar seekBar;
    private ImageButton playRecord,img_btn_return;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    SimpleDateFormat format;
    private AudioManager audioManager;
    private Timer timer;
    private boolean isPlaying = false;
    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。
    private User user;

    private LinearLayout body;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_page);

        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        format = new SimpleDateFormat("mm:ss");
        getViews();

        sleepInfo = (SleepInfo) getIntent().getExtras().getSerializable("sleepInfo");
        //获取数据库中睡眠记录的信息
        getDate();


        img_btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecordPage.this, MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);            }
        });
    }

    private void getDate() {
        String URL = Constant.BASE_URL+ "sleep/findSleepInfoById?sleepId="+sleepInfo.getSleepId();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URL)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("onFailure", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                Result result = gson.fromJson(string, new TypeToken<Result<SleepInfo>>(){}.getType());
                SleepInfo sleepInfo1 = (SleepInfo) result.getData();
                //更新界面
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setOnSeekBarChangeListener(new MySeekBar());
                        //开始时间和结束时间设置
                        setTime(sleepInfo1);
                        //获取音频
                        initMediaPlayer();
                        //设置录音的播放
                        setListener();
                    }
                });
            }
        });
    }

    private void initMediaPlayer() {
        try {
            mediaPlayer.setDataSource(getExternalCacheDir().getAbsolutePath()+"/audiorecordtest"+sleepInfo.getSleepId()+".3gp");//指定音频文件的路径
            mediaPlayer.prepare();//让mediaplayer进入准备状态
            mediaPlayer.setLooping(true);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    seekBar.setMax(mediaPlayer.getDuration());
                    length.setText(format.format(mediaPlayer.getDuration())+"");
                    cur.setText("00:00");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setListener() {
        playRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    //监听播放时回调函数
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        Runnable updateUI = new Runnable() {
                            @Override
                            public void run() {
                                cur.setText(format.format(mediaPlayer.getCurrentPosition())+"");
                                if (cur.getText().equals(length.getText())) {
                                    stop();
                                }
                            }
                        };

                        @Override
                        public void run() {
                            if (!isSeekBarChanging) {
                                seekBar.setProgress(mediaPlayer.getCurrentPosition());
                                runOnUiThread(updateUI);
                            }
                        }
                    }, 0, 50);

                } else {
                    mediaPlayer.pause();
                }
            }
        });
    }

    private void stop() {
        mediaPlayer.pause();
        mediaPlayer.seekTo(0);
        setListener();
    }

    private void setTime(SleepInfo sleepInfo) {
        String time1 = sleepInfo.getAsleepTime().split(" ")[1];
        String time2 = sleepInfo.getAwakeTime().split(" ")[1];
        arpSleep.setText(time1.split(":")[0]+":"+time1.split(":")[1]);
        arpWeakUp.setText(time2.split(":")[0]+":"+time2.split(":")[1]);

        arpSleepDay.setText(sleepInfo.getAsleepTime().split(" ")[0]);
        arpWeakUpDay.setText(sleepInfo.getAwakeTime().split(" ")[0]);
    }

    private void getViews() {
        arpSleep = (TextView) findViewById(R.id.arp_sleep);
        arpWeakUp = (TextView) findViewById(R.id.arp_weakUp);
        arpSleepDay = (TextView) findViewById(R.id.arp_sleepDay);
        arpWeakUpDay = (TextView) findViewById(R.id.arp_weakUpDay);
        seekBar = findViewById(R.id.seekBar);
        cur = (TextView) findViewById(R.id.cur);
        length = (TextView) findViewById(R.id.length);
        playRecord = (ImageButton) findViewById(R.id.play_record);
        img_btn_return = (ImageButton) findViewById(R.id.img_btn_return);
        body = findViewById(R.id.body);
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mediaPlayer.seekTo(seekBar.getProgress());
        }
    }
}